package com.cos.shop.dao.impl;

import com.cos.shop.dao.CartDao;
import com.cos.shop.entity.Cart;
import com.cos.shop.util.DBUtils;
import com.cos.shop.vo.CartVo;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: COS
 * @time: 2023/5/11 11:33
 * @description:
 */
public class CartDaoImpl implements CartDao {
    private QueryRunner qr = new QueryRunner(DBUtils.getDataSource());

    @Override
    public int clearCart(int uid) throws SQLException {
        return qr.update("delete from cart where u_id = ?",uid);
    }

    @Override
    public int deleteCartByUidAnsPid(int pid, int uid) throws SQLException {
        return qr.update("delete from cart where u_id = ? and p_id = ?",uid,pid);
    }

    @Override
    public Cart getCartByUidAndPid(int uid, int goodsId) throws SQLException {
        String sql = "select " +
                        "  `c_id` 'cid'," +
                        "  `u_id` 'uid'," +
                        "  `p_id` 'pid'," +
                        "  `c_count` 'ccount'," +
                        "  `c_num` 'cnum' " +
                        "from cart where u_id = ? and p_id=?";
        return qr.query(sql, new BeanHandler<>(Cart.class),
                uid,goodsId);
    }

    @Override
    public int updateCart(Cart c) throws SQLException {
        String sql = "update cart set c_count = ? ,c_num = ? where c_id=?";
        return qr.update(sql,c.getCcount(),c.getCnum(),c.getCid());
    }

    @Override
    public List<CartVo> getCartWithProByUid(int uid) throws SQLException {
        String sql = "select " +
                "  `c_id` 'cid'," +
                "  `u_id` 'uid'," +
                "  c.`p_id` 'pid'," +
                "  `c_count` 'ccount'," +
                "  `c_num` 'cnum' ," +
                "  `p_name` 'pname' ," +
                "  `p_price` 'pprice' " +
                "from cart c inner join product p" +
                " on c.p_id=p.p_id" +
                " where u_id = ?";
        return qr.query(sql,new BeanListHandler<>(CartVo.class),uid);
    }

    @Override
    public int addCart(Cart cart) throws SQLException {
        String sql = "INSERT INTO `cart`  VALUES ( DEFAULT, ?, ?, ?, ? )";
        return qr.update(sql,
                cart.getUid(),cart.getPid(),cart.getCcount(),cart.getCnum());
    }
}
